package com.hb.trade.api.routine.controller.project.calibration;


import cn.hutool.core.collection.CollUtil;
import com.hb.core.pojo.Attachment;
import com.hb.core.pojo.Attachments;
import com.hb.core.pojo.enums.NewsTypeEnum;
import com.hb.core.pojo.enums.NewsTypeTwoEnum;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.calibration.dto.BidWinResultDTO;
import com.hb.core.pojo.project.calibration.dto.BidWinResultSupplyDTO;
import com.hb.core.pojo.project.deal.dto.BidCandidateSupplierDTO;
import com.hb.trade.api.routine.service.PortalNoticeService;
import com.hb.trade.api.routine.sms.annotation.SmsSend;
import com.hb.trade.api.routine.util.SendNewsUtil;
import com.hb.trade.client.project.BidWinResultClient;
import com.hb.trade.client.project.DealClient;
import com.hb.trade.client.project.SectionClient;
import fzzn.core.aspose.convert.AsposeConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.auth.shiro.util.ShiroUtil;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.msg.ResponseDto;
import org.fzzn.core.util.ResultUtil;
import org.fzzn.core.web.anno.Version;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;

/**
 * <p>
 * 中标结果公示/公告表 前端控制器
 * </p>
 *
 * @author zhongdl
 * @since 2021-12-18
 */
@Slf4j
@Version(1.0)
@Api(tags = {"中标结果公示"})
@RequestMapping("/{version}")
@RestController
public class ApiBidWinResultController {


    protected final BidWinResultClient bidWinResultClient;
    protected final DealClient dealClient;
    protected final SectionClient sectionClient;
    protected final PortalNoticeService portalNoticeService;

    public ApiBidWinResultController(BidWinResultClient bidWinResultClient,
                                     DealClient dealClient,
                                     SectionClient sectionClient,
                                     PortalNoticeService portalNoticeService) {
        this.bidWinResultClient = bidWinResultClient;
        this.dealClient = dealClient;
        this.sectionClient = sectionClient;
        this.portalNoticeService = portalNoticeService;
    }

    @ApiOperation(value = "初始化中标结果公告信息 新增中标结果公告返回项目信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Long.class),
    })
    @PostMapping("/bidWinResult/initWinResultInfo")
    public ResponseDto initWinResultInfo(@RequestBody BidWinResultDTO bidWinResult) {
        if(bidWinResult.getProjectId() == null){
          return ResultUtil.fail(MsgEnum.INCORRECT_PARAM);
        }
        Message<BidWinResultDTO> bidWinResultDTOMessage =  bidWinResultClient.initWinResultInfo(bidWinResult);
        return ResultUtil.msg(bidWinResultDTOMessage);
    }


    @ApiOperation(value = "中标结果公示详情接口", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "中标结果id", dataTypeClass = Long.class),
    })
    @PostMapping("/bidWinResult/bidWinResultInfo")
    public ResponseDto bidWinResultInfo(@RequestBody BidWinResultDTO bidWinResult) {
        if(bidWinResult.getId() == null){
            return ResultUtil.fail(MsgEnum.INCORRECT_PARAM);
        }
        Message<BidWinResultDTO> bidWinResultDTOMessage =  bidWinResultClient.bidWinResultInfoDetail(bidWinResult);
        return ResultUtil.msg(bidWinResultDTOMessage);
    }




    @ApiOperation(value = "保存中标结果结果", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "中标结果id", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "sectionId", value = "标段id", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "noticeNature", value = "公告性质 1.首次公告 2 变更公告", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "noticeTitle", value = "公告标题", dataTypeClass = String.class),
            @ApiImplicitParam(name = "noticeContent", value = "公告内容", dataTypeClass = String.class),
            @ApiImplicitParam(name = "medium", value = "公告媒介", dataTypeClass = String.class),
            @ApiImplicitParam(name = "attachment", value = "附件", dataTypeClass = Attachments.class),
            @ApiImplicitParam(name = "pushFlag", value = "是否推送", dataTypeClass = Integer.class),
    })
    @PostMapping("/bidWinResult/saveBidWinResult")
    public ResponseDto saveBidWinResult(@RequestBody BidWinResultDTO bidWinResult) {
        // 1: 中标结果公告基本信息保存 * 2: 中标结果公告第二部文件内容更新
        if (CollUtil.isNotEmpty(bidWinResult.getContentUrl())){
            Attachment attachment = bidWinResult.getContentUrl().get(0);
            File thisFile = attachment.getThisFile();
            String htmlStr = AsposeConvertUtil.wordToHtml(thisFile);
            bidWinResult.setNoticeContent(htmlStr);

        }
        //设置创建人和更新人
        if (bidWinResult.getId() == null){
            bidWinResult.setCreateName(ShiroUtil.getUser().getFullName());
        }else {
            bidWinResult.setUpdateName(ShiroUtil.getUser().getFullName());
        }
        Message<BidWinResultDTO> saveMsg;
        if (Integer.valueOf(1).equals(bidWinResult.getNoticeFormFlag())){
            saveMsg =  bidWinResultClient.saveBidWinResult(bidWinResult);
        }else {
            saveMsg = bidWinResultClient.updateNoticeContent(bidWinResult);
        }

        return ResultUtil.msg(saveMsg);
    }


    @ApiOperation(value = "发布中标结果", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "中标结果id", dataTypeClass = Long.class),
    })
    @SmsSend(type = 10)
    @PostMapping("/bidWinResult/releaseBidWinResult")
    public ResponseDto releaseBidWinResult(@RequestBody BidWinResultDTO bidWinResult) {
        //发布中标结果公告
        Long id = bidWinResult.getId();
        if (id == null){
            return ResultUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        Message<Boolean> saveMsg =  bidWinResultClient.releaseBidWinResult(bidWinResult);
        //给投标人发送消息

        Message<BidWinResultDTO> bidWinResultDTOMessage = bidWinResultClient.bidWinResultInfoDetail(bidWinResult);
        if (bidWinResultDTOMessage.isFail() ||bidWinResultDTOMessage.getData() == null){
            return ResultUtil.msg(saveMsg);
        }
        BidWinResultDTO bidWinResultDTO = bidWinResultDTOMessage.getData();

        // 将中标结果推送只门户公告
        portalNoticeService.pushWidResultToPortal(bidWinResult.getId());

        //查询参与该标段的投标人
        List<BidWinResultSupplyDTO> successfulNoticeSupplyList = bidWinResultDTO.getSuccessfulNoticeSupplyList();
        for (BidWinResultSupplyDTO bidWinResultSupplyDTO : successfulNoticeSupplyList) {
            Message<List<Long>> longUserIds = sectionClient.listParticipateSection(bidWinResultSupplyDTO.getSectionId());
            if (longUserIds.isFail() || CollUtil.isEmpty(longUserIds.getData())){
                continue;
            }
            List<Long> receiverIds = longUserIds.getData();
            //发送消息
            SendNewsUtil.sendBiddereeNews(
                    bidWinResultSupplyDTO.getSectionId(),
                    NewsTypeEnum.PROJECT_CHANGE,
                    NewsTypeTwoEnum.NOTICE_PROJECT_CHANGE,
                    "中标结果公示",
                    null,
                    "/console/bidResultNotice",
                    receiverIds
            );
        }

        return ResultUtil.msg(saveMsg);
    }


    @ApiOperation(value = "保存并且发布中标结果公告", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "中标结果id", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "sectionId", value = "标段id", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "noticeNature", value = "公告性质 1.首次公告 2 变更公告", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "noticeTitle", value = "公告标题", dataTypeClass = String.class),
            @ApiImplicitParam(name = "noticeContent", value = "公告内容", dataTypeClass = String.class),
            @ApiImplicitParam(name = "medium", value = "公告媒介", dataTypeClass = String.class),
            @ApiImplicitParam(name = "attachment", value = "附件", dataTypeClass = Attachments.class),
            @ApiImplicitParam(name = "pushFlag", value = "是否推送", dataTypeClass = Integer.class),
    })
    @PostMapping("/bidWinResult/saveReleaseBidWinResult")
    @SmsSend(type = 10)
    public ResponseDto saveReleaseBidWinResult(@RequestBody BidWinResultDTO bidWinResult) {
        if (CollUtil.isNotEmpty(bidWinResult.getContentUrl())){
            Attachment attachment = bidWinResult.getContentUrl().get(0);
            File thisFile = attachment.getThisFile();
            String htmlStr = AsposeConvertUtil.wordToHtml(thisFile);
            bidWinResult.setNoticeContent(htmlStr);

        }
        if (bidWinResult.getId() == null){
            bidWinResult.setCreateName(ShiroUtil.getUser().getFullName());
        }else {
            bidWinResult.setUpdateName(ShiroUtil.getUser().getFullName());
        }
        // 1: 中标结果公告基本信息保存 * 2: 中标结果公告第二部文件内容更新
        Message<BidWinResultDTO> saveMsg = bidWinResultClient.updateNoticeContent(bidWinResult);
         if (saveMsg.isFail()){
             return ResultUtil.FAIL;
         }
         //发布接口
         Message<Boolean> releaseBidWinResult =  bidWinResultClient.releaseBidWinResult(bidWinResult);
        //给投标人发送消息

        Message<BidWinResultDTO> bidWinResultDTOMessage = bidWinResultClient.bidWinResultInfoDetail(bidWinResult);
        if (bidWinResultDTOMessage.isFail() ||bidWinResultDTOMessage.getData() == null){
            return ResultUtil.msg(releaseBidWinResult);
        }
        BidWinResultDTO bidWinResultDTO = bidWinResultDTOMessage.getData();

        // 将中标结果推送只门户公告
        portalNoticeService.pushWidResultToPortal(bidWinResult.getId());

        //查询参与该标段的投标人
        List<BidWinResultSupplyDTO> successfulNoticeSupplyList = bidWinResultDTO.getSuccessfulNoticeSupplyList();
        for (BidWinResultSupplyDTO bidWinResultSupplyDTO : successfulNoticeSupplyList) {
            Message<List<Long>> longUserIds = sectionClient.listParticipateSection(bidWinResultSupplyDTO.getSectionId());
            if (longUserIds.isFail() || CollUtil.isEmpty(longUserIds.getData())){
                continue;
            }
            List<Long> receiverIds = longUserIds.getData();
            //发送消息
            SendNewsUtil.sendBiddereeNews(
                    bidWinResultSupplyDTO.getSectionId(),
                    NewsTypeEnum.PROJECT_CHANGE,
                    NewsTypeTwoEnum.NOTICE_PROJECT_CHANGE,
                    "中标结果公示",
                    null,
                    "/console/bidResultNotice",
                    receiverIds
            );
        }
         return ResultUtil.msg(releaseBidWinResult);
    }


    @ApiOperation(value = "根据项目id查询中标结果列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Long.class),
    })
    @PostMapping("/bidWinResult/pageBidWinResult")
    public ResponseDto pageBidWinResult(@RequestBody BidWinResultDTO bidWinResult) {
        if(bidWinResult.getProjectId() == null){
            return ResultUtil.fail(MsgEnum.INCORRECT_PARAM);
        }
        //查询中标结果列表
        Message<PageResult<BidWinResultDTO>> pageResultMessage = bidWinResultClient.pageBidWinResult(bidWinResult);

        return ResultUtil.msg(pageResultMessage);
    }


    @ApiOperation(value = "根据标段id查询中标结果列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", dataTypeClass = Long.class),
    })
    @PostMapping("/bidWinResult/pageBidWinResultBySectionId")
    public ResponseDto pageBidWinResultBySectionId(@RequestBody BidWinResultDTO bidWinResult) {
        if(bidWinResult.getSectionId() == null){
            return ResultUtil.fail(MsgEnum.INCORRECT_PARAM);
        }
        //查询中标结果列表
        Message<PageResult<BidWinResultDTO>> pageResultMessage = bidWinResultClient.pageBidWinResultBySectionId(bidWinResult);

        return ResultUtil.msg(pageResultMessage);
    }

    @ApiOperation(value = "查询未新建中标结果公告并且标段状态未已结束的的标段列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Long.class),
    })
    @PostMapping("/bidWinResult/pageNotSelectBidSection")
    public ResponseDto pageNotSelectBidSection(@RequestBody BidWinResultDTO bidWinResult) {
        if(bidWinResult.getProjectId() == null){
            return ResultUtil.fail(MsgEnum.INCORRECT_PARAM);
        }
        //查询中标结果列表
        Message<PageResult<BidWinResultDTO>> pageResultMessage = bidWinResultClient.pageNotSelectBidSection(bidWinResult);
        return ResultUtil.msg(pageResultMessage);
    }
    @ApiOperation(value = "查询中标人列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "项目id", dataTypeClass = Long.class),
    })

    @PostMapping("/bidWinResult/listSuccessfulBidder")
    public ResponseDto listSuccessfulBidder(@RequestBody BidCandidateSupplierDTO successfulNoticeSupply) {
        if(successfulNoticeSupply.getSectionId() == null){
            return ResultUtil.fail(MsgEnum.INCORRECT_PARAM);
        }
        //查询中标候选人结果列表
        BidCandidateSupplierDTO bidCandidateSupplierDTO = new BidCandidateSupplierDTO();
        successfulNoticeSupply.to(bidCandidateSupplierDTO);
        Message<PageResult<BidCandidateSupplierDTO>> pageResultMessage = dealClient.pageCandidate(bidCandidateSupplierDTO);


        return ResultUtil.msg(pageResultMessage);
    }

    @ApiOperation(value = "查询中标结果包含的标段信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", dataTypeClass = Long.class),
    })

    @PostMapping("/bidWinResult/pageIncludeBidSection")
    public ResponseDto pageIncludeBidSection(@RequestBody BidWinResultSupplyDTO successfulNoticeSupply) {
        if(successfulNoticeSupply.getId() == null){
            return ResultUtil.fail(MsgEnum.INCORRECT_PARAM);
        }
        //查询中标结果列表
        Message<PageResult<BidWinResultSupplyDTO>> pageResultMessage = bidWinResultClient.pageIncludeBidSection(successfulNoticeSupply);
        return ResultUtil.msg(pageResultMessage);
    }

}
